package org.example.cloudgetway.config;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.example.cloudgetway.util.BaseResult;
import org.example.cloudgetway.util.JwtUtils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
@ConfigurationProperties(prefix = "org.my.jwt")
@Data
public class LongGlobalFilter implements GlobalFilter, Ordered {

    /*
* org:
  my:
    jwt:
      skipAuthUrls:
        - /usr/login
* */
    private String[] AuthUrls;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        List<String> list = new ArrayList<>();
        list.add("/usr/login");


        String url = exchange.getRequest().getURI().getPath();
        if (AuthUrls != null && isSkipUrl(url,AuthUrls)){
            System.out.println("true");
            return chain.filter(exchange);
        }

        // 获取token
        String token = exchange.getRequest().getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)){
            return create(exchange,BaseResult.ok("令牌空"));
        }
        boolean verify = JwtUtils.verify(token);
        if (!verify){
            return create(exchange,BaseResult.ok("令牌失效"));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> create(ServerWebExchange exchange, BaseResult result){
        System.out.println("create");
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
        byte[] bytes = JSON.toJSONString(result).toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer wrap = response.bufferFactory().wrap(bytes);
        return response.writeWith(Flux.just(wrap));
    }

    public boolean isSkipUrl(String url,String[] list){
        System.out.println("url==>"+url);
        for (String skipAuthUrl : list) {
            if (url.startsWith(skipAuthUrl)){
                return true;
            }else {
                return false;
            }
        }
        return false;
    }
}
